/*
 * Copyright (c) 2023, LXMS (lxinet.cn).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.lxinet.lxms.framework.mybatis.service;

import cn.lxinet.lxms.framework.core.helper.PageHelper;
import cn.lxinet.lxms.framework.core.vo.Page;
import cn.lxinet.lxms.framework.mybatis.conditions.SqlWrapper;
import cn.lxinet.lxms.framework.mybatis.mapper.BaseMapper;
import cn.lxinet.lxms.framework.mybatis.helper.TableHelper;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

/**
 * service方法封装
 *
 * @author zcx
 * @date 2023/07/25
 */
public class SimpleService<T> {
    @Autowired
    private BaseMapper<T> baseMapper;
    private Class<?> tClass;

    @PostConstruct
    public void init() {
        this.tClass = getTClass();
        TableHelper.initTable(tClass);
    }

    public T findById(Long id) {
        return baseMapper.selectById(id, tClass);
    }

    public List<T> listAll() {
        SqlWrapper<T> sqlWrapper = new SqlWrapper(tClass);
        return baseMapper.selectList(sqlWrapper);
    }

    public List<T> listAll(SqlWrapper<T> sqlWrapper) {
        return baseMapper.selectList(sqlWrapper);
    }

    public List<T> listByPage() {
        SqlWrapper<T> sqlWrapper = new SqlWrapper(tClass);
        return baseMapper.selectPage(PageHelper.getPage(), sqlWrapper);
    }

    public List<T> listByPage(Page page, SqlWrapper<T> sqlWrapper) {
        return baseMapper.selectPage(page, sqlWrapper);
    }

    public List<T> listByIds(List<Long> ids) {
        return baseMapper.selectByIds(ids, tClass);
    }

    public void insert(T t) {
        baseMapper.insert(t);
    }

    public void batchInsert(Collection<T> list) {
        baseMapper.batchInsert(list, tClass);
    }

    public void updateById(T t) {
        baseMapper.updateById(t);
    }

    public boolean delete(T t) {
        return baseMapper.delete(t) > 0;
    }

    public boolean deleteById(Long id) {
        return baseMapper.deleteById(id, tClass) > 0;
    }

    private Class<T> getTClass() {
        Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return tClass;
    }
}
